//
//  UIPopoverListView.m
//  UIPopoverListViewDemo
//
//  Created by su xinde on 13-3-13.
//  Copyright (c) 2013年 su xinde. All rights reserved.
//

#import "UIPopoverListView.h"
#import <QuartzCore/QuartzCore.h>
#import "UIView+Addtions.h"

//#define FRAME_X_INSET 20.0f
//#define FRAME_Y_INSET 40.0f

@interface UIPopoverListView () {
    UIInterfaceOrientation currentOrient;
}

@property (nonatomic, strong) UIButton *addButton;

- (void)defalutInit;
- (void)fadeIn;
- (void)fadeOut;

@end

@implementation UIPopoverListView

@synthesize datasource = _datasource;
@synthesize delegate = _delegate;

@synthesize listView = _listView;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self defalutInit];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame withStyle:(PopoverStyle)popoverStyle {
    self = [super initWithFrame:frame];
    if (self) {
        _popoverStyle = popoverStyle;
        switch (_popoverStyle) {
            case DefaultStyle:
                [self defalutInit];
                break;
            case FeedBackStyle:
                [self initWithFeedBackView];
                break;
            case DatePickerStyle:
                // TODO: ADD here
                [self initWithDatePickerView];
                break;
            default:
                break;
        }
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)initWithFeedBackView {
    [self addBaseSubviews];
    
    self.backgroundColor = [UIColor whiteColor];
    CGFloat xWidth = self.bounds.size.width;
    CGFloat padding = 5;
    CGRect textViewFrame = CGRectMake(padding, TitleHeight+padding, xWidth-padding*2, self.bounds.size.height-TitleHeight-padding*2);
    _textView = [[UITextView alloc] initWithFrame:textViewFrame];
//    _textView.backgroundColor = [UIColor lightGrayColor];
    [self addSubview:_textView];
    
    _titleView.textAlignment = NSTextAlignmentLeft;
    _titleView.text = @"  添加反馈";
    
    self.addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_addButton addTarget:self action:@selector(addButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [_addButton setImage:[UIImage imageNamed:@"img_addBtn"] forState:UIControlStateNormal];
    [_addButton sizeToFit];
    
    [self addSubview:_addButton];
    _addButton.right = xWidth - padding*2;
    _addButton.centerY = TitleHeight*0.5;
}

- (void)initWithDatePickerView {
    [self addBaseSubviews];
    self.backgroundColor = [UIColor whiteColor];
    CGFloat xWidth = self.bounds.size.width;
    CGFloat padding = 5;
    CGRect pickerViewFrame = CGRectMake(padding, TitleHeight+padding, xWidth-padding*2, self.bounds.size.height-TitleHeight-padding*2);
    _datePicker = [[UIDatePicker alloc] init];
    if (CurrentDeviceISiPad) {
        _datePicker.frame = CGRectMake(0, 0, xWidth, self.bounds.size.height-TitleHeight);
//        _datePicker.backgroundColor = [UIColor redColor];
    } else {
        _datePicker.frame = pickerViewFrame;
    }
//    [_datePicker addTarget:self action:@selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
    _datePicker.datePickerMode =  UIDatePickerModeDate;
    _datePicker.locale = [NSLocale currentLocale];
    
    [self addSubview:_datePicker];
    
    _titleView.textAlignment = NSTextAlignmentLeft;
    _titleView.text = @"  选择日期";
    
    self.addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_addButton addTarget:self action:@selector(addButtonPressed2:) forControlEvents:UIControlEventTouchUpInside];
    [_addButton setImage:[UIImage imageNamed:@"btn_ic_done"] forState:UIControlStateNormal];
    [_addButton sizeToFit];
    
    [self addSubview:_addButton];
    _addButton.right = xWidth - padding*2;
    _addButton.centerY = TitleHeight*0.5;
}

- (void)setPickerDate:(NSDate *)date {
    _datePicker.date = date;
}

- (void)addButtonPressed:(id)sender {
    if (_delegate && [_delegate respondsToSelector:@selector(addFeedBackContent:)]) {
        [_delegate addFeedBackContent:_textView.text];
    }
}

- (void)addButtonPressed2:(id)sender {
    [self dismiss];
    if (_delegate && [_delegate respondsToSelector:@selector(selectDateAt:)]) {
        [_delegate selectDateAt:_datePicker.date];
    }
}

- (void)defalutInit
{
    [self addBaseSubviews];
    CGFloat xWidth = self.bounds.size.width;
    CGRect tableFrame = CGRectMake(0, TitleHeight, xWidth, self.bounds.size.height-TitleHeight);
    _listView = [[UITableView alloc] initWithFrame:tableFrame style:UITableViewStylePlain];
    _listView.dataSource = self;
    _listView.delegate = self;
    [self addSubview:_listView];
}

- (void)addBaseSubviews {

    self.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    self.layer.borderWidth = 1.0f;
    
    _titleView = [[UILabel alloc] initWithFrame:CGRectZero];
    _titleView.font = [UIFont boldSystemFontOfSize:24.0f];
    
    _titleView.backgroundColor = COLOR(54, 147, 190);
    
    _titleView.textAlignment = NSTextAlignmentCenter;
    _titleView.textColor = [UIColor whiteColor];
    CGFloat xWidth = self.bounds.size.width;
    _titleView.lineBreakMode = NSLineBreakByTruncatingTail;
    _titleView.frame = CGRectMake(0, 0, xWidth, TitleHeight); //32.0f
    [self addSubview:_titleView];
    
    _overlayView = [[UIControl alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    _overlayView.backgroundColor = [UIColor colorWithRed:.16 green:.17 blue:.21 alpha:.5];
    [_overlayView addTarget:self
                     action:@selector(dismiss)
           forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(self.datasource &&
       [self.datasource respondsToSelector:@selector(popoverListView:numberOfRowsInSection:)])
    {
        return [self.datasource popoverListView:self numberOfRowsInSection:section];
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.datasource &&
       [self.datasource respondsToSelector:@selector(popoverListView:cellForIndexPath:)])
    {
        return [self.datasource popoverListView:self cellForIndexPath:indexPath];
    }
    return nil;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.delegate &&
       [self.delegate respondsToSelector:@selector(popoverListView:heightForRowAtIndexPath:)])
    {
        return [self.delegate popoverListView:self heightForRowAtIndexPath:indexPath];
    }
    
    return 0.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.delegate &&
       [self.delegate respondsToSelector:@selector(popoverListView:didSelectIndexPath:)])
    {
        [self.delegate popoverListView:self didSelectIndexPath:indexPath];
    }
    
    [self dismiss];
}


#pragma mark - animations

- (void)fadeIn
{
    self.transform = CGAffineTransformMakeScale(1.3, 1.3);
    self.alpha = 0;
    [UIView animateWithDuration:.35 animations:^{
        self.alpha = 1;
        self.transform = CGAffineTransformMakeScale(1, 1);
    }];
    
}
- (void)fadeOut
{
    [UIView animateWithDuration:.35 animations:^{
        self.transform = CGAffineTransformMakeScale(1.3, 1.3);
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        if (finished) {
            [_overlayView removeFromSuperview];
            [self removeFromSuperview];
            if (_delegate && [_delegate respondsToSelector:@selector(dismissFromParentView:)]) {
                [_delegate dismissFromParentView:self];
            }
        }
    }];
}

- (void)setTitle:(NSString *)title
{
    _titleView.text = title;
    _titleView.font = [UIFont boldSystemFontOfSize:20];
}

- (void)show
{
    UIWindow *keywindow = [[UIApplication sharedApplication] keyWindow];
    [keywindow addSubview:_overlayView];
    [keywindow addSubview:self];


    if (CurrentDeviceISiPad&&!IsiOS8Over) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationChange2) name:UIDeviceOrientationDidChangeNotification object:nil];
        [self deviceOrientationChange];
    }
    self.center = CGPointMake(keywindow.bounds.size.width/2.0f,
                              keywindow.bounds.size.height/2.0f);
    if (_textView) {
        [_textView becomeFirstResponder];
        if (CurrentDeviceISiPad) {
            UIInterfaceOrientation tempOrient= [UIApplication sharedApplication].statusBarOrientation;
            if (tempOrient == UIInterfaceOrientationLandscapeLeft) {
                self.centerX -= 100;
            } else if (tempOrient == UIInterfaceOrientationLandscapeRight) {
                self.centerX += 100;
            }
        } else {
            self.top -= ISFourInch?60:105;
        }
    }
    
    [self fadeIn];
}

- (void)deviceOrientationChange2 {

    UIInterfaceOrientation tempOrient= [UIApplication sharedApplication].statusBarOrientation;
    if (currentOrient != tempOrient) {
        currentOrient = tempOrient;
    } else {
        return;
    }
    CGAffineTransform rightTransform = CGAffineTransformRotate(self.transform, M_PI);
    self.transform = rightTransform;
    if (_textView && CurrentDeviceISiPad) {
        UIWindow *keywindow = [[UIApplication sharedApplication] keyWindow];
        self.center = CGPointMake(keywindow.bounds.size.width/2.0f,
                                  keywindow.bounds.size.height/2.0f);
        if (tempOrient == UIInterfaceOrientationLandscapeLeft) {
            self.centerX -= 100;
        } else if (tempOrient == UIInterfaceOrientationLandscapeRight) {
            self.centerX += 100;
        }
    }
}

- (void)deviceOrientationChange {
    UIInterfaceOrientation tempOrient= [UIApplication sharedApplication].statusBarOrientation;
    if (currentOrient != tempOrient) {
        currentOrient = tempOrient;
    } else {
        return;
    }
    if (currentOrient == UIInterfaceOrientationLandscapeRight) //UIDeviceOrientationLandscapeRight
    {
        NSLog(@"right ...");
        CGAffineTransform rightTransform = CGAffineTransformMake(0.0, 1.0, -1.0, 0.0, 0.0, 0.0);
        self.transform = rightTransform;
        CGFloat width = self.width;
        self.width = self.height;
        self.height = width;
        _listView.transform = rightTransform;
        _textView.transform = rightTransform;
        _datePicker.transform = rightTransform;
        _titleView.transform = rightTransform;
        _addButton.transform = rightTransform;
        _titleView.origin = CGPointMake(self.height-TitleHeight, 0);
        _addButton.centerX = self.height - TitleHeight*0.5;
        _addButton.centerY = self.width - TitleHeight*0.5;
        _listView.origin = CGPointMake(0, 0);
        _textView.origin = CGPointMake(0, 0);
        _datePicker.origin = CGPointMake(10, 0);
        _datePicker.centerY = self.width*0.5;
    }
    else if(currentOrient == UIInterfaceOrientationLandscapeLeft)//UIDeviceOrientationLandscapeLeft
    {
        NSLog(@"left ...");
        CGAffineTransform leftTransform = CGAffineTransformMake(0.0, -1.0, 1.0, 0.0, 0.0, 0.0);
        self.transform = leftTransform;
        CGFloat width = self.width;
        self.width = self.height;
        self.height = width;
        _listView.transform = leftTransform;
        _textView.transform = leftTransform;
        _datePicker.transform = leftTransform;
        _titleView.transform = leftTransform;
        _addButton.transform = leftTransform;
        _titleView.origin = CGPointMake(0, 0);
        _listView.origin = CGPointMake(TitleHeight, 0);
        _textView.origin = CGPointMake(TitleHeight, 0);
        _addButton.centerX = _addButton.centerY = TitleHeight*0.5;
        _datePicker.origin = CGPointMake(TitleHeight+10, 0);
        _datePicker.centerY = self.width*0.5;
    }
}

- (void)addToParentView {
    
    [_parentView addSubview:_overlayView];
    [_parentView addSubview:self];

    self.center = CGPointMake(_parentView.bounds.size.width/2.0f,
                              _parentView.bounds.size.height/2.0f);
    [self fadeIn];
}

- (void)addToParentViewFullScreen {
    
//    _overlayView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
    _overlayView.frame = CGRectMake(0, 0, AppWidth, AppHeight);
    
    [_parentView addSubview:_overlayView];
    [_parentView addSubview:self];
    
    self.center = CGPointMake(_parentView.bounds.size.width/2.0f,
                              _parentView.bounds.size.height/2.0f);
    [self fadeIn];
}

- (void)addToParentViewWithFrame:(CGRect)rect {
    _overlayView.frame = rect;
    
    [_parentView addSubview:_overlayView];
    [_parentView addSubview:self];
    
    self.center = CGPointMake(rect.size.width/2.0f+rect.origin.x,
                              rect.size.height/2.0f);
    [self fadeIn];
}

- (void)dismiss
{
    [self fadeOut];
}

#define mark - UITouch
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    // tell the delegate the cancellation
    if (self.delegate && [self.delegate respondsToSelector:@selector(popoverListViewCancel:)]) {
        [self.delegate popoverListViewCancel:self];
    }
    
    // dismiss self
    [self dismiss];
}

@end
